// pages/index/index.js
Page({
    data: {
        // 游戏区域的宽度和高度（以格子为单位）
        gameWidth: 20,
        gameHeight: 20,
        // 蛇的初始位置和方向
        snake: [
            { x: 5, y: 5 },
            { x: 4, y: 5 },
            { x: 3, y: 5 }
        ],
        direction: 'right',
        // 食物的位置
        food: { x: 10, y: 10 },
        // 游戏是否开始
        gameStarted: false,
        // 游戏是否结束
        gameOver: false,
        // 游戏得分
        score: 0
    },
    onLoad() {
        this.calculateCanvasSize(); // 添加此行初始化画布尺寸
        // 显示游戏开始提示
        wx.showModal({
            title: '游戏开始',
            content: '点击确定开始游戏',
            success: (res) => {
                if (res.confirm) {
                    this.setData({
                        gameStarted: true
                    });
                    this.startGame();
                }
            }
        });
    },
    startGame() {
        // 开始游戏循环
        this.gameInterval = setInterval(() => {
            this.moveSnake();
            this.checkCollision();
            this.checkEatFood();
            this.draw();
        }, 200);
    },
    moveSnake() {
        let { snake, direction } = this.data;
        let head = { ...snake[0] };
        switch (direction) {
            case 'right':
                head.x++;
                break;
            case 'left':
                head.x--;
                break;
            case 'up':
                head.y--;
                break;
            case 'down':
                head.y++;
                break;
        }
        snake.unshift(head);
        snake.pop();
        this.setData({
            snake
        });
    },
    checkCollision() {
        let { snake, gameWidth, gameHeight } = this.data;
        let head = snake[0];
        // 检查是否撞到墙壁（已正确使用动态尺寸）
        if (head.x < 0 || head.x >= gameWidth || head.y < 0 || head.y >= gameHeight) {
            this.gameOver();
            return;
        }
        // 检查是否撞到自己
        for (let i = 1; i < snake.length; i++) {
            if (head.x === snake[i].x && head.y === snake[i].y) {
                this.gameOver();
                return;
            }
        }
    },
    checkEatFood() {
        let { snake, food } = this.data;
        let head = snake[0];
        if (head.x === food.x && head.y === food.y) {
            // 蛇吃到食物，增长身体
            let newHead = { ...head };
            snake.unshift(newHead);
            // 生成新的食物
            this.generateFood();
            // 增加得分
            this.setData({
                score: this.data.score + 1
            });
        }
    },
    generateFood() {
        let { gameWidth, gameHeight, snake } = this.data;
        let newFood;
        do {
            newFood = {
                x: Math.floor(Math.random() * gameWidth),
                y: Math.floor(Math.random() * gameHeight)
            };
        } while (this.isFoodOnSnake(newFood, snake));
        this.setData({
            food: newFood
        });
    },
    isFoodOnSnake(food, snake) {
        for (let i = 0; i < snake.length; i++) {
            if (food.x === snake[i].x && food.y === snake[i].y) {
                return true;
            }
        }
        return false;
    },
    gameOver() {
        // 停止游戏循环
        clearInterval(this.gameInterval);
        this.setData({
            gameOver: true
        });
        wx.showModal({
            title: '游戏结束',
            content: `你的得分是：${this.data.score}`,
            success: (res) => {
                if (res.confirm) {
                    // 重新开始游戏
                    this.setData({
                        snake: [
                            { x: 5, y: 5 },
                            { x: 4, y: 5 },
                            { x: 3, y: 5 }
                        ],
                        direction: 'right',
                        food: { x: 10, y: 10 },
                        gameStarted: false,
                        gameOver: false,
                        score: 0
                    });
                    this.onLoad();
                }
            }
        });
    },
    changeDirection(e) {
        let { direction } = this.data;
        let newDirection = e.currentTarget.dataset.direction;
        // 防止蛇反向移动
        if (
            (direction === 'right' && newDirection === 'left') ||
            (direction === 'left' && newDirection === 'right') ||
            (direction === 'up' && newDirection === 'down') ||
            (direction === 'down' && newDirection === 'up')
        ) {
            return;
        }
        this.setData({
            direction: newDirection
        });
    },
calculateCanvasSize() {
  wx.getSystemInfo({
    success: (res) => {
      const safeArea = res.safeArea;
      const availableHeight = safeArea.height * 0.7;
      const canvasWidth = safeArea.width * 0.95;
      // 先计算画布高度临时变量
      const canvasHeight = Math.min(availableHeight, canvasWidth * 1.2);
      const gridSize = Math.max(10, Math.min(
        Math.floor(canvasWidth / 20),
        Math.floor(canvasHeight / 20)
      ));
      // 1. 计算整数格子数（关键修复）
      const gameWidth = Math.floor(canvasWidth / gridSize);
      const gameHeight = Math.floor(canvasHeight / gridSize);
      // 2. 调整画布尺寸为网格的整数倍（关键修复）
      const adjustedCanvasWidth = gameWidth * gridSize;
      const adjustedCanvasHeight = gameHeight * gridSize;
      this.setData({
        canvasWidth: adjustedCanvasWidth,  // 使用调整后的整数尺寸
        canvasHeight: adjustedCanvasHeight,
        gridSize: gridSize,
        gameWidth: gameWidth,
        gameHeight: gameHeight
      }, () => this.data.gameStarted && !this.data.gameOver && this.draw());
    }
  });
},

// 绘制游戏元素
 draw() {
  const ctx = wx.createCanvasContext('snakeCanvas', this);
  const { canvasWidth, canvasHeight, snake, food, gridSize } = this.data;

  // 清空画布
  ctx.clearRect(0, 0, canvasWidth, canvasHeight);

  // 绘制蛇
  snake.forEach((segment, index) => {
    // 蛇头使用亮绿色，蛇身使用绿色渐变
    ctx.setFillStyle(index === 0 ? '#4CAF50' : '#8BC34A');
    ctx.fillRect(
      segment.x * gridSize,
      segment.y * gridSize,
      gridSize - 2,
      gridSize - 2
    );
    // 蛇头添加眼睛
    if (index === 0) {
      ctx.setFillStyle('white');
      const eyeSize = gridSize / 5;
      const eyeOffset = gridSize / 4;
      // 根据方向绘制眼睛位置
      switch(this.data.direction) {
        case 'right':
          ctx.beginPath();
          ctx.arc(segment.x * gridSize + gridSize - eyeOffset, segment.y * gridSize + eyeOffset, eyeSize, 0, 2 * Math.PI);
          ctx.arc(segment.x * gridSize + gridSize - eyeOffset, segment.y * gridSize + gridSize - eyeOffset, eyeSize, 0, 2 * Math.PI);
          ctx.fill();
          break;
        case 'left':
          ctx.beginPath();
          ctx.arc(segment.x * gridSize + eyeOffset, segment.y * gridSize + eyeOffset, eyeSize, 0, 2 * Math.PI);
          ctx.arc(segment.x * gridSize + eyeOffset, segment.y * gridSize + gridSize - eyeOffset, eyeSize, 0, 2 * Math.PI);
          ctx.fill();
          break;
        case 'up':
          ctx.beginPath();
          ctx.arc(segment.x * gridSize + eyeOffset, segment.y * gridSize + eyeOffset, eyeSize, 0, 2 * Math.PI);
          ctx.arc(segment.x * gridSize + gridSize - eyeOffset, segment.y * gridSize + eyeOffset, eyeSize, 0, 2 * Math.PI);
          ctx.fill();
          break;
        case 'down':
          ctx.beginPath();
          ctx.arc(segment.x * gridSize + eyeOffset, segment.y * gridSize + gridSize - eyeOffset, eyeSize, 0, 2 * Math.PI);
          ctx.arc(segment.x * gridSize + gridSize - eyeOffset, segment.y * gridSize + gridSize - eyeOffset, eyeSize, 0, 2 * Math.PI);
          ctx.fill();
          break;
      }
    }
  });

  // 绘制食物（黄色圆形）
  ctx.setFillStyle('#FFEB3B');
  ctx.beginPath();
  ctx.arc(
    food.x * gridSize + gridSize / 2,
    food.y * gridSize + gridSize / 2,
    gridSize / 2 - 1,
    0, 2 * Math.PI
  );
  ctx.fill();

  ctx.draw();
}
});
